package com.etrans.baf.analyse.task.swap.service;

import java.text.ParseException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.mybatis.spring.SqlSessionTemplate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.etrans.baf.analyse.util.BaseService;
import com.etrans.baf.analyse.util.Constants;
import com.etrans.baf.analyse.util.DateUtils;
import com.etrans.baf.analyse.util.SpringWebContextUtil;
import com.etrans.baf.analyse.util.Sysconfig;
import com.etrans.baf.analyse.util.XmlReader;
import com.mongodb.BasicDBObject;
import com.mongodb.CommandResult;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;

@Service
public class PlatformService extends BaseService {

	@Autowired
	private MongoTemplate egovMongoTemplate;// 引入配置的mongod模版

	public PlatformService() {
		super.masterAliases = "com.etrans.baf.analyse.task.swap.persistence.swapMapper";
	}

	@Override
	protected SqlSessionTemplate getMasterSessionTemplate() {
		return (SqlSessionTemplate) SpringWebContextUtil
				.getApplicationContext().getBean("dataSourceMasterSession");
	}

	/**
	 * 获取行业信息
	 * 
	 * @return
	 */
	private List<HashMap<String, Object>> getTradeInfo() {
		return (List<HashMap<String, Object>>) this
				.select("getTradeInfo", null);
	}

	/**
	 * 平台分析
	 * 
	 * @throws Exception
	 */
	public void platformSwap(String analyse_date,int num) throws Exception{
		//先删除后新增
		Date analyseDate = DateUtils.parse(analyse_date,Constants.DATE_YYYY_MM_DD);
		String dirUrl=System.getProperty("analyse")+Sysconfig.getPropValueByCode("swap");
    	String table_date= DateUtils.format(analyseDate, Constants.DATE_YYMMDD);
    	if(num==0){
    		List<HashMap<String,Object>> trade = getTradeInfo();
    		if(trade!=null && trade.size()>0){
    			DBObject scope = new BasicDBObject();
                for (HashMap hashMap : trade) {
                	DBObject obj = new BasicDBObject();
                	obj.put("trade_name", hashMap.get("trade_name"));
                	obj.put("vehicle_count",0);
                	obj.put("vehicle_access_count",0);
                	obj.put("vehicle_online_count",0);
                	obj.put("alarm_vehicle_count",0);
                	obj.put("vehicle_access_rate",0.0);
                	obj.put("vehicle_online_rate",0.0);
                	obj.put("alarm_vehicle_rate",0.0);
                	obj.put("alarm_count",0.0);
                	obj.put("alarm_processed",0);
                	obj.put("overspeed_count",0);
                	obj.put("overspeed_processed",0);
                	obj.put("tired_count",0);
                	obj.put("tired_processed",0);
                	obj.put("avg_overspeed_count",0);
                	obj.put("avg_tired_count",0);
                	obj.put("alarm_processed_rate",0.0);
                	scope.put(String.valueOf(hashMap.get("id")), obj);
				}
	    		Query query = Query.query(Criteria.where("analyse_date").is(analyseDate));
	        	int dcount = egovMongoTemplate.remove(query,"platform_swap").getN();
	        	mapReducePlatform(dirUrl, analyse_date, table_date,scope);
    		}else{
    			logger.info("没有行业信息,不让分析平台分析");
    		}
    	}else if(num==1){//链路
    		mapReduceLink(dirUrl, analyse_date, table_date);
    	}
	}

	/**
     * 业务维度中间表分析
     * @param dirUrl 文件目录地址
     * @param analyse_date yyyy-MM-dd
     * @param table_date yyMMdd
     * @param scope 行业对象信息
     * @throws Exception
     */
	private void mapReducePlatform(String dirUrl, String analyse_date,
			String table_date, DBObject scope) throws Exception {
		Map<String, String> exp = XmlReader.readXmlToMapReduce(dirUrl
				+ "platform_swap.xml");
		if (exp != null && exp.size() > 0) {
			DBObject command = new BasicDBObject();
			DBObject sort = new BasicDBObject();
			sort.put("_id", 1);
			DBObject query = new BasicDBObject();
			query.put("analyse_date",
					DateUtils.parse(analyse_date, Constants.DATE_YYYY_MM_DD));
			command.put("mapreduce", "vehicle_swap");
			command.put("query", query);
			command.put("map", exp.get("map0"));
			command.put("reduce", exp.get("reduce0"));
			command.put("out", "platform_swap_temp0");
			command.put("sort", sort);// analyse_date
			CommandResult result = egovMongoTemplate.executeCommand(command);
			boolean ok = result.ok();
			logger.info("平台分析第一步platform_swap_temp0"+(ok?"成功":"失败,原因"+result.getErrorMessage()));
			if (ok) {// 入库更新
				command.put("mapreduce", "platform_swap_temp0");
				command.removeField("query");
				command.put("map", exp.get("map"));
				command.put("reduce", exp.get("reduce"));
				String tradeObj = JSON.toJSONString(scope);
	    		String finalizeStr = exp.get("finalize").replaceAll("TRADE_OBJ", tradeObj);
				command.put("finalize",finalizeStr );
				command.put("out", "platform_swap_temp");
				command.removeField("sort");
				CommandResult result2 = egovMongoTemplate.executeCommand(command);
				logger.info("平台分析第二步platform_swap_temp"+(result2.ok()?"成功":"失败,原因"+result2.getErrorMessage()));
				if(result2.ok()){
					String update = exp.get("update").replaceAll("DATE_YYMMDD",
							table_date);
					egovMongoTemplate.getDb().doEval(update);// 追加
				}
			}
		}
	}

	/**
	 * 业务维度中间表分析 链路
	 * 
	 * @param dirUrl
	 *            文件目录地址
	 * @param analyse_date
	 *            yyyy-MM-dd
	 * @param table_date
	 *            yyMMdd
	 * @throws Exception
	 */
	private void mapReduceLink(String dirUrl, String analyse_date,
			String table_date) throws Exception {
		Map<String, String> exp = XmlReader.readXmlToMapReduce(dirUrl
				+ "vehicle_swap_sub_link_log.xml");
		if (exp != null && exp.size() > 0) {
			DBObject command = new BasicDBObject();
			DBObject sort = new BasicDBObject();
			sort.put("gnsscenter_id", 1);
			sort.put("time", -1);
			DBObject query = new BasicDBObject();
			DBObject time = new BasicDBObject();
			time.put("$lte", DateUtils.parse(analyse_date + " 23:59:59.999"));// 小于等于
			query.put("time", time);
			command.put("mapreduce", "sub_link_log");
			command.put("query", query);
			command.put("map", exp.get("map"));
			command.put("reduce", exp.get("reduce"));
			String last_day = DateUtils.getAnalyseDate(analyse_date, -1);
			String fin = exp.get("finalize")
					.replaceAll("DATE_YYYY_MM_DD1_STR", last_day)
					.replaceAll("DATE_YYYY_MM_DD_STR", analyse_date);
			command.put("finalize", fin);
			command.put("out", "vehicle_swap_sub_link_log");
			command.put("sort", sort);// analyse_date
			CommandResult result = egovMongoTemplate.executeCommand(command);
			boolean ok = result.ok();
			if (ok) {// 入库更新
				String update = exp.get("update").replaceAll("DATE_YYMMDD",
						table_date);
				egovMongoTemplate.getDb().doEval(update);// 追加
			}
		}
	}

	/**
	 * 平台得分设置
	 * 
	 * @param analyse_date
	 * @throws Exception
	 */
	public void updateScore(String analyse_date) throws Exception {
		String dirUrl = System.getProperty("analyse")
				+ Sysconfig.getPropValueByCode("swap");
		Map<String, String> map = XmlReader.readXmlToMapReduce(dirUrl
				+ "score_swap.xml");
		if (map != null) {
			String last_date = DateUtils.getAnalyseDate(analyse_date, -1);// 取上一天
			String update = map.get("platformScore").replaceAll(
					"DATE_YYYY_MM_DD", last_date);
			egovMongoTemplate.getDb().doEval(update);
			logger.info("修改平台得分--------");
		}
	}
	/**2017-11-15 此方法目前无用了
	 * 周月 季度 当月 年分析表得分
	 */
	public void updateScoreWMSY(String analyse_date,int type) throws Exception{
		String dirUrl=System.getProperty("analyse")+Sysconfig.getPropValueByCode("swap");
		Map<String,String> map = XmlReader.readXmlToMapReduce(dirUrl+"score_WMSY.xml");
        if(map!=null){
        	String insert_table="";
        	if(type==Constants.PLATFORM_ANALYSE_W){
        		insert_table="platform_swap_week";
        	}else if(type==Constants.PLATFORM_ANALYSE_M){
        		insert_table="platform_swap_month";
        	}else if(type==Constants.PLATFORM_ANALYSE_S){
        		insert_table="platform_swap_season";
        	}else if(type==Constants.PLATFORM_ANALYSE_Y){
        		insert_table="platform_swap_year";
        	}else if(type==Constants.PLATFORM_ANALYSE_CM){
        		insert_table="platform_swap_curMonth";
        	}
        	String last_date = DateUtils.getAnalyseDate(analyse_date, -1);//取上一天
        	String update = map.get("platformScore").replaceAll("DATE_YYYY_MM_DD", last_date).replaceAll("PLATFORM_TABLE", insert_table);
    		egovMongoTemplate.getDb().doEval(update);
    		logger.info("----修改"+insert_table+"平台得分--------");
        }
	}
	/**
	 * 周月季年分析
	 * @param analyse_date 分析的首日
	 * @type 0周 1月 2季度 3年度
	 * @throws Exception
	 */
	public void platformWMSY(String start_date,String end_date,int type) throws Exception{
		//Date startDate = DateUtils.parse(start_date,Constants.DATE_YYYY_MM_DD);
		//Date endDate = DateUtils.parse(end_date,Constants.DATE_YYYY_MM_DD);
		String dirUrl=System.getProperty("analyse")+Sysconfig.getPropValueByCode("swap");
		//String YYMMDD = DateUtils.format(startDate, Constants.DATE_YYMMDD);
		List<HashMap<String,Object>> trade = getTradeInfo();
		if(trade!=null && trade.size()>0){
			DBObject scope = new BasicDBObject();
            for (HashMap hashMap : trade) {
            	DBObject obj = new BasicDBObject();
            	obj.put("trade_name", hashMap.get("trade_name"));
            	obj.put("vehicle_count",0);
            	obj.put("vehicle_access_count",0);
            	obj.put("vehicle_online_count",0);
            	obj.put("alarm_vehicle_count",0);
            	obj.put("vehicle_access_rate",0.0);
            	obj.put("vehicle_online_rate",0.0);
            	obj.put("alarm_vehicle_rate",0.0);
            	obj.put("alarm_count",0.0);
            	obj.put("alarm_processed",0);
            	obj.put("overspeed_count",0);
            	obj.put("overspeed_processed",0);
            	obj.put("tired_count",0);
            	obj.put("tired_processed",0);
            	obj.put("avg_overspeed_count",0);
            	obj.put("avg_tired_count",0);
            	obj.put("alarm_processed_rate",0.0);
            	scope.put(String.valueOf(hashMap.get("id")), obj);
			}
            /*String analyse_date = DateUtils.getAnalyseDate(start_date,-1);//mongodb 日期-8小时
            analyseWMSY(dirUrl, startDate, endDate, scope, type,YYMMDD,analyse_date);*/
            analyseWeekMonth(dirUrl, start_date, end_date, scope, type);
		}else{
			logger.info("没有行业信息,不让分析平台月 周 季度 年表");
		}    	 
	}
	/**
	 * 周 月 当月的区域分析
	 * @throws Exception 
	 */
	private void analyseWeekMonth(String dirUrl,String startDate,String endDate,DBObject scope,int type) throws Exception{
		Map<String,String> exp = XmlReader.readXmlToMapReduce(dirUrl+"platform_swap_weekMonth.xml");
        if(exp!=null&& exp.size()>0){
        	DBObject command = new BasicDBObject();
       	DBObject sort = new BasicDBObject();
       	sort.put("_id",1);
       	DBObject query = new BasicDBObject();
       	String mrtable="";
       	String out_table="";
        String insert_table="";
        String YYYY_MM_DD_S="";
        String YYYY_MM_DD_E="";
        String YYMMDD="";
       	if(type==Constants.PLATFORM_ANALYSE_W){
       		query.put("analyse_date",DateUtils.parse(startDate, Constants.DATE_YYYY_MM_DD));
       		mrtable="vehicle_swap_week";
       		out_table="platform_swap_temp_week";
    		insert_table="platform_swap_week";
    		YYMMDD=startDate.substring(2,10).replaceAll("-", "");
    		YYYY_MM_DD_S=DateUtils.getAnalyseDate(startDate, -1);//前一天
    		YYYY_MM_DD_E=DateUtils.getAnalyseDate(endDate, -1);//前一天
       	}else if(type==Constants.PLATFORM_ANALYSE_M){
       		query.put("analyse_date",DateUtils.parse(endDate.substring(0,7)+"-01", Constants.DATE_YYYY_MM_DD));
       		mrtable="vehicle_swap_month";
       		out_table="platform_swap_temp_month";
    		insert_table="platform_swap_month";
    		YYMMDD=endDate.substring(2,7).replaceAll("-", "")+"01";
    		YYYY_MM_DD_S=DateUtils.getAnalyseDate(startDate, -1);//前一天
    		YYYY_MM_DD_E=DateUtils.getAnalyseDate(endDate, -1);//前一天
       	}else if(type==Constants.PLATFORM_ANALYSE_CM){
       		mrtable="vehicle_swap_curMonth";
    		insert_table="platform_swap_curMonth";
    		out_table="platform_swap_temp_curMonth";
    		String current_mon_day = DateUtils.format(new Date(),Constants.DATE_YYYY_MM_DD);
			String day = current_mon_day.substring(current_mon_day.length()-2,current_mon_day.length());
			if(Integer.parseInt(day)<=25){//当前月  25分析
				YYMMDD=endDate.substring(2,7).replaceAll("-", "")+"01";
	    		YYYY_MM_DD_S=DateUtils.getAnalyseDate(startDate, -1);//前一天
	    		
			}else{//分析下个月
				String  startDateStr=DateUtils.nextMonthFirstDate();
				Date start=DateUtils.parse(startDateStr,Constants.DATE_YYYY_MM_DD);
	    		YYMMDD = DateUtils.format(start, Constants.DATE_YYMMDD);
	    		YYYY_MM_DD_S=DateUtils.getAnalyseDate(startDate, -1);
			}
			String beforeone  = DateUtils.getAnalyseDate(current_mon_day, -1);//前一天
    		YYYY_MM_DD_E=DateUtils.getAnalyseDate(beforeone, -1);//实际的分析结束日期(mongodb里面是前一天的16:00结束)
    	}
       	String outtable0="platform_"+type;
       	command.put("mapreduce",mrtable);
       	command.put("query", query);
       	command.put("map",exp.get("map0"));
       	command.put("reduce",exp.get("reduce0"));
       	command.put("out",outtable0); 
       	command.put("sort", sort);
       	CommandResult result = egovMongoTemplate.executeCommand(command);
       	boolean ok = result.ok();
        logger.info("创建平台"+outtable0+(ok?"成功":"失败:"+result.getErrorMessage()));
       	if(ok){//入库更新
       			command.put("mapreduce",outtable0);
       			command.removeField("query");
       			command.put("map",exp.get("map"));
       	       	command.put("reduce",exp.get("reduce"));
       	       	String tradeObj = JSON.toJSONString(scope);
	     		String finalizeStr = exp.get("finalize").replaceAll("TRADE_OBJ", tradeObj);
	     		command.put("finalize",finalizeStr);
	     		command.put("out",out_table); 
	     		command.removeField("sort");
	     		CommandResult result2 = egovMongoTemplate.executeCommand(command);
	     		logger.info("创建平台"+out_table+(result2.ok()?"成功":"失败:"+result2.getErrorMessage()));
	     		if(result2.ok()){
		        	String update = exp.get("update").replaceAll("DATE_YYMMDD",YYMMDD).replaceAll("PARAM_PLATFORM_INSERT", insert_table).replaceAll("PARAM_PLATFORM_TABLE", out_table).replaceAll("YYYY_MM_DD_S", YYYY_MM_DD_S).replaceAll("YYYY_MM_DD_E", YYYY_MM_DD_E);
		        	egovMongoTemplate.getDb().doEval(update);//追加
	        	    logger.info("分析成功"+out_table);
	     		}
	     }
        }
	}
	/**2017-11-15 此方法已经有替代方法 analyseWeekMonth
	 * 周 月 当月 季度 年的区域分析
	 * @throws Exception 
	 */
	private void analyseWMSY(String dirUrl,Date startDate,Date endDate,DBObject scope,int type,String YYMMDD,String analyse_date) throws Exception{
		Map<String,String> exp = XmlReader.readXmlToMapReduce(dirUrl+"platform_swap_WMSY.xml");
        if(exp!=null&& exp.size()>0){
        	DBObject command = new BasicDBObject();
       	DBObject sort = new BasicDBObject();
       	sort.put("_id",1);
       	DBObject query = new BasicDBObject();
       	DBObject time = new BasicDBObject();
       	time.put("$gte", startDate);
       	time.put("$lte", endDate);
       	query.put("analyse_date",time);
       	command.put("mapreduce","platform_swap");
       	command.put("query", query);
       	command.put("map",exp.get("map"));
       	command.put("reduce",exp.get("reduce"));
       	String tradeObj = JSON.toJSONString(scope);
		String finalizeStr = exp.get("finalize").replaceAll("TRADE_OBJ", tradeObj);
		command.put("finalize",finalizeStr);
    	String out_table="";
        String insert_table="";
    	if(type==Constants.PLATFORM_ANALYSE_W){
    		out_table="platform_swap_temp_week";
    		insert_table="platform_swap_week";
    	}else if(type==Constants.PLATFORM_ANALYSE_M){
    		out_table="platform_swap_temp_month";
    		insert_table="platform_swap_month";
    		startDate=DateUtils.parse(DateUtils.format(endDate, Constants.DATE_YYYY_MM)+"-01", Constants.DATE_YYYY_MM_DD);
    		YYMMDD = DateUtils.format(startDate, Constants.DATE_YYMMDD);
    		String  startDateStr= DateUtils.format(startDate, Constants.DATE_YYYY_MM_DD);
    		analyse_date=DateUtils.getAnalyseDate(startDateStr,-1);//mongodb 日期-8小时
    	}else if(type==Constants.PLATFORM_ANALYSE_S){
    		out_table="platform_swap_temp_season";
    		insert_table="platform_swap_season";
    	}else if(type==Constants.PLATFORM_ANALYSE_Y){
    		insert_table="platform_swap_year";
    		out_table="platform_swap_temp_year";
    	}else if(type==Constants.PLATFORM_ANALYSE_CM){
    		insert_table="platform_swap_curMonth";
    		out_table="platform_swap_temp_curMonth";
    		String current_mon_day = DateUtils.format(new Date(),Constants.DATE_YYYY_MM_DD);
			String day = current_mon_day.substring(current_mon_day.length()-2,current_mon_day.length());
			if(Integer.parseInt(day)<=25){//当前月
				startDate=DateUtils.parse(DateUtils.format(endDate, Constants.DATE_YYYY_MM)+"-01", Constants.DATE_YYYY_MM_DD);
	    		YYMMDD = DateUtils.format(startDate, Constants.DATE_YYMMDD);
	    		String  startDateStr= DateUtils.format(startDate, Constants.DATE_YYYY_MM_DD);
	    		analyse_date=DateUtils.getAnalyseDate(startDateStr,-1);//mongodb 日期-8小时
			}else{//分析下个月
				String  startDateStr=DateUtils.nextMonthFirstDate();
				startDate=DateUtils.parse(startDateStr,Constants.DATE_YYYY_MM_DD);
	    		YYMMDD = DateUtils.format(startDate, Constants.DATE_YYMMDD);
	    		analyse_date=DateUtils.getAnalyseDate(startDateStr,-1);//mongodb 日期-8小时
			}

    	}
       	command.put("out",out_table); 
       	command.put("sort", sort);
       	CommandResult result = egovMongoTemplate.executeCommand(command);
       	boolean ok = result.ok();
        logger.info("创建区域"+out_table+(ok?"成功":"失败:"+result.getErrorMessage()));
       	if(ok){//入库更新
				Query rquery = Query.query(Criteria.where("analyse_date").is(startDate));
        	    int dcount = egovMongoTemplate.remove(rquery,insert_table).getN();
        	    logger.info("删除"+insert_table+"数据"+dcount);
	        	String update = exp.get("update").replaceAll("DATE_YYMMDD",YYMMDD).replaceAll("PARAM_PLATFORM_INSERT", insert_table).replaceAll("PARAM_PLATFORM_TABLE", out_table).replaceAll("DATE_YY_MM_DD", analyse_date);
	        	egovMongoTemplate.getDb().doEval(update);//追加
        	    logger.info("分析成功"+out_table);
	     }
        }
	}
}
